package com.hyg.module_user.systemSetting;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hyg.lib_base.MyView.MyWheelView;
import com.hyg.lib_base.lisener.AppUpdateListener;
import com.hyg.lib_base.lisener.PermissionListener;
import com.hyg.lib_base.mainUtils.GlideCacheUtil;
import com.hyg.lib_base.mainUtils.PackageUtils;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.TypeFaceUtil.TypeFaceData;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.SQLite.MyDataBaseHelper;
import com.hyg.lib_common.ThirdSDK.PuGongYing;
import com.hyg.lib_common.WebView.WebViewActivity;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.listener.LoginStateListener;
import com.hyg.lib_common.loginpart.LoginByCodeActivity;
import com.hyg.lib_common.loginpart.LoginFasterUtil;
import com.hyg.lib_common.sweetalertdialog.MyDialog;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.hyg.module_user.R;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;

@Route(path = Constants.PATH_ACTIVITY_MODULE_USER_SYSTEMSETTING)
public class SystemSettingActivity extends BaseActivity {

    private ImageView back;
    private RelativeLayout login_out, clear_cache, change_textsize, check_update, change_typeface;
    private RelativeLayout suggest, aboutus;
    private RelativeLayout show_privacy;
    private TextView tv_cache_size, tv_change_textsize, app_version, tv_change_text_typeface;
    private Switch change_music_mobile_switch;
    private String CacheSize;
    private int TextStates = 0;
    private SeekBar seekBar;
    private MyWheelView wheel_texttype;
    private MyDataBaseHelper dbHelper;
    private List<String> data = new ArrayList<>();
    private ArrayList<TypeFaceData> al_TypeFaceData = new ArrayList<>();
    private String[] Styles = {"正常字体", "粗体", "斜体", "粗斜体"};
    private int[] TypeStyles = {Typeface.NORMAL, Typeface.BOLD, Typeface.ITALIC, Typeface.BOLD_ITALIC};
    private MyHandler myHandler;
    ProgressBar progressBar;

    LoginFasterUtil loginFasterUtil;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup);
        init();
    }


    @SuppressLint("HandlerLeak")
    public void init() {
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 00, null, null, true);
        initView();
        initData();
    }

    public void initView() {
        suggest = findViewById(R.id.suggest);
        aboutus = findViewById(R.id.aboutus);
        check_update = findViewById(R.id.check_update);
        app_version = findViewById(R.id.app_version);
        change_music_mobile_switch = findViewById(R.id.change_music_mobile_switch);
        show_privacy = findViewById(R.id.show_privacy);
        //调整字号和字体
        change_textsize = findViewById(R.id.change_textsize);
        tv_change_textsize = findViewById(R.id.tv_change_textsize);
        change_typeface = findViewById(R.id.change_typeface);
        tv_change_text_typeface = findViewById(R.id.tv_change_text_typeface);
        CacheSize = GlideCacheUtil.getInstance().getCacheSize(this);
        tv_cache_size = findViewById(R.id.tv_cache_size);
        tv_cache_size.setText("当前缓存大小：" + CacheSize);
        clear_cache = findViewById(R.id.clear_cache);
        back = findViewById(R.id.back);
        login_out = findViewById(R.id.login_out);

        setTypeFaceList();
        String texttemp = ssu.getString("TypeFace", "");
        for (int i = 0; i < al_TypeFaceData.size(); i++) {
            if (texttemp.equals(al_TypeFaceData.get(i).getFilePath())) {
                tv_change_text_typeface.setText("当前字体: " + al_TypeFaceData.get(i).getChineseName());
                break;
            }
        }
        TextStates = ssu.getInt("TextSize", 0);
        if (0 == TextStates) {
            tv_change_textsize.setText("当前字号:最小");
        } else if (1 == TextStates) {
            tv_change_textsize.setText("当前字号: 小");
        } else if (2 == TextStates) {
            tv_change_textsize.setText("当前字号: 中");
        } else if (3 == TextStates) {
            tv_change_textsize.setText("当前字号: 大");
        } else {
            tv_change_textsize.setText("当前字号:最大");
        }
        initListener();
    }

    public void initListener() {
        /** 返回*/
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                SystemSettingActivity.this.finish();
                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }
        });

        /** 退出登录*/
        login_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pDialog.isShowing())
                    pDialog.dismiss();
                pDialog = new SweetAlertDialog(SystemSettingActivity.this, SweetAlertDialog.NORMAL_TYPE);
                pDialog.setTitleText("确定注销当前账号？");  //(/n自动清除本机报告数据)
                pDialog.setConfirmButton("确定", new SweetAlertDialog.OnSweetClickListener() {
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        setLogin_out();
                    }
                });
                pDialog.setCancelButton("取消", new SweetAlertDialog.OnSweetClickListener() {
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                });
                pDialog.show();
            }
        });

        /** 清除glide的使用缓存*/
        clear_cache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pDialog.isShowing())
                    pDialog.dismiss();
                pDialog = new SweetAlertDialog(SystemSettingActivity.this, SweetAlertDialog.WARNING_TYPE);
                pDialog.setTitleText("清理缓存？");
                pDialog.setContentText("当前缓存大小：" + CacheSize);
                pDialog.setConfirmButton("确定", new SweetAlertDialog.OnSweetClickListener() {
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        CacheSize = GlideCacheUtil.getInstance().clearImageAllCache(getApplication());
                        tv_cache_size.setText("当前缓存大小：" + CacheSize);
                        sweetAlertDialog.dismiss();
                    }
                });
                pDialog.setCancelButton("取消", new SweetAlertDialog.OnSweetClickListener() {
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                });
                pDialog.show();
            }
        });

        /** 改变字号大小*/
        change_textsize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnClickSeekbar(TextStates);
            }
        });
        change_typeface.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(SetUp.this,SetUpTypeFace.class));
//                overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });

        /** 是否允许移动网络下载音乐*/
        change_music_mobile_switch.setChecked(UserSPUtils.getAllowMobile(this));
        change_music_mobile_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    UserSPUtils.setAllowMobile(SystemSettingActivity.this, true);
                } else {
                    UserSPUtils.setAllowMobile(SystemSettingActivity.this, false);
                }
            }
        });

        /** 检测更新*/
        check_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick())
                    return;
                String[] needPermissions = {
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.REQUEST_INSTALL_PACKAGES,
                };
                getPermissions(needPermissions, new PermissionListener() {
                    @Override
                    public void onResult(int[] results) {
                        if (results[0] != 0) {
                            Toast.makeText(SystemSettingActivity.this, "此应用需要用户授予读写权限", Toast.LENGTH_LONG).show();
                        } else {
                            check_version_update(true, true);
                        }
                    }
                });
            }
        });
        app_version.setText("当前版本 V" + PackageUtils.getVersionName(getApplication()));

        /** 意见反馈*/
        suggest.setOnClickListener(new View.OnClickListener() {                 //
            @Override
            public void onClick(View v) {
                ToIntent(Constants.PATH_ACTIVITY_MODULE_USER_SETTING_SUGGEST, false);
                overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });

        /** 关于我们*/
        aboutus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToIntent(Constants.PATH_ACTIVITY_MODULE_USER_SETTING_ABOUTUS, false);
                overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });

        /** 免责声明*/
        show_privacy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(SystemSettingActivity.this, WebViewActivity.class);
                it.putExtra("url", UrlUtils.PrivacyUrl);
                it.putExtra("title", "隐私政策与免责声明");
                //                it.putExtra("type","Privacy");
                startActivity(it);
                overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });
    }

    public void initData() {
        dbHelper = new MyDataBaseHelper(SystemSettingActivity.this);
        db = dbHelper.getReadableDatabase();//得到一个可写的数据库
        myHandler = new MyHandler(this);
    }

    private static class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private SystemSettingActivity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (SystemSettingActivity) reference.get();
        }

        public void handleMessage(Message msg) {
            if (msg.what == 1) {//保存用户 修改信息
                try {
                    JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                    String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                    String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
                    if (status.equals("200")) {
                        UserSPUtils.clearUserInfo(activity);
//                        activity.ToIntent(Constants.PATH_ACTIVITY_WELCOME, true);
                        activity.loginFasterUtil=new LoginFasterUtil(activity);
                        activity.loginFasterUtil.startLoginView(new LoginStateListener() {
                            @Override
                            public void OnStart(int Type) {
                                Log.i("lgb", "OnStart: " + Type);
                            }

                            @Override
                            public void OnSuccess() {
                                activity.ToIntent(Constants.PATH_ACTIVITY_MAIN,true);
                                activity.overridePendingTransition(R.anim.fade, R.anim.hold);
                                activity.finish();
                            }

                            @Override
                            public void OnFail(String Message) {
                                Log.i("lgb", "OnFail: 11111" + Message);
                                activity.finishAffinity();
                            }

                            @Override
                            public void OnCancel(String Message) {
//                    finish();
                                activity.finishAffinity();
                            }

                            @Override
                            public void OnOpenFail(String Message) {
                                Intent intent = new Intent(activity, LoginByCodeActivity.class);
                                activity.startActivity(intent);
                                activity.overridePendingTransition(R.anim.fade, R.anim.hold);
                                activity.finish();
                            }
                        });
                    } else {
                        activity.ErrorDialog(message);
                    }
                } catch (JSONException | UnsupportedEncodingException e) {
                    Log.d(CrashTAG, "" + e.getMessage());
                }
            }
        }


    }

    public void setTypeFaceList() {
        al_TypeFaceData.add(new TypeFaceData("系统默认", ""));
        al_TypeFaceData.add(new TypeFaceData("微软雅黑", "font/wryh.ttf"));
        al_TypeFaceData.add(new TypeFaceData("楷体", "font/simkai.ttf"));
        al_TypeFaceData.add(new TypeFaceData("宋体", "font/stsong.ttf"));
        al_TypeFaceData.add(new TypeFaceData("幼圆", "font/SIMYOU.TTF"));
        al_TypeFaceData.add(new TypeFaceData("隶书", "font/simli.ttf"));
        al_TypeFaceData.add(new TypeFaceData("黑体", "font/simhei.ttf"));
        al_TypeFaceData.add(new TypeFaceData("等线", "font/Deng.ttf"));
        al_TypeFaceData.add(new TypeFaceData("仿宋", "font/simfang.ttf"));
        al_TypeFaceData.add(new TypeFaceData("方正舒体", "font/FZYTK.TTF"));
        al_TypeFaceData.add(new TypeFaceData("方正姚体", "font/FZSTK.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文彩云", "font/STCAIYUN.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文仿宋", "font/STFANGSO.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文琥珀", "font/STHUPO.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文楷体", "font/STKAITI.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文隶书", "font/STLITI.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文宋体", "font/STSONG.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文细黑", "font/STXIHEI.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文行楷", "font/STXINGKA.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文新魏", "font/STXINWEI.TTF"));
        al_TypeFaceData.add(new TypeFaceData("华文中宋", "font/STZHONGS.TTF"));
    }

    /**
     * description:   改变字号  滑动seekbar监听
     *
     * @param textSize 初始字号
     * @author visitant
     * @time 2020/12/2 10:15
     */
    public void OnClickSeekbar(int textSize) {
        data.clear();
        for (int i = 0; i < Styles.length; i++) {
            data.add(Styles[i]);
        }
        View view = View.inflate(this, R.layout.dialog_seekbar, null);
        seekBar = (SeekBar) view.findViewById(R.id.seekBar);
        wheel_texttype = (MyWheelView) view.findViewById(R.id.wheel_texttype);
        if (!Utils.isEmpty(ssu.getInt("TypeStyle", 0))) {
            for (int i = 0; i < TypeStyles.length; i++)
                if (ssu.getInt("TypeStyle", 0) == (TypeStyles[i])) {
                    wheel_texttype.setDataWithSelectedItemIndex(data, i);
                    break;
                }
        } else {
            wheel_texttype.setDataWithSelectedItemIndex(data, 0);
        }
        wheel_texttype.setWheelViewSelectedListener(new MyWheelView.IWheelViewSelectedListener() {
            public void wheelViewSelectedChanged(MyWheelView myWheelView, List<String> data, int position) {
//                Log.d("wheel", "wheelViewSelectedChanged: " + data.get(position));
//                textView.setText(data.get(position));
            }
        });

        seekBar.setProgress(textSize);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.NORMAL_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#7b40be"));
        pDialog.setTitleText("字体调节(选好后自动重启)");
        pDialog.setCustomView(view);
        pDialog.setConfirmButton("选好啦", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                SetThemes(seekBar.getProgress(), wheel_texttype.getSelectedItemIndex());
                sweetAlertDialog.dismiss();
            }
        });
        pDialog.setCancelButton("取消", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });
        pDialog.show();
    }


    /*    设置字体风格和字号，后重启生效    */
    public void SetThemes(int textsize, int typeStyle) {
        editorn = ssu.edit();
        editorn.putInt("TextSize", textsize);
        editorn.putInt("TypeStyle", typeStyle);
//        editorn.putString("TypeFace",FONTS[typeface_num]);
        editorn.commit();
        restartApp2();
    }

    /**
     * 重新启动App -> 杀进程,会短暂黑屏,启动慢
     */
    public void restartApp() { //启动页
//        Intent intent = new Intent(MyApp.getInstance(), MainActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        MyApp.getInstance().startActivity(intent);
//        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 重新启动App -> 不杀进程,缓存的东西不清除,启动快
     */
    public void restartApp2() {
        final Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }


    public void check_version_update(final boolean IsShowText,boolean isSystemSetting) {
        new PuGongYing().getUpdateVersion(this, IsShowText, isSystemSetting,new AppUpdateListener() {
            @Override
            public void onStart() {
                AlertDialog.Builder builder = new AlertDialog.Builder(SystemSettingActivity.this);
                updateDialog = builder.create();
                updateDialog=new MyDialog(SystemSettingActivity.this, com.hyg.lib_common.R.style.alert_dialog_light);
                View dialogView = View.inflate(SystemSettingActivity.this, com.hyg.lib_common.R.layout.dialog_update_version, null);
                TextView TvContent=dialogView.findViewById(com.hyg.lib_common.R.id.content_tv);
                TvContent.setText("应用更新中,请稍候...");
                progressBar=dialogView.findViewById(com.hyg.lib_common.R.id.progress_bar);
                updateDialog.setView(dialogView);
                updateDialog.setCancelable(false);
                updateDialog.show();
            }

            @Override
            public void onProgress(int progress) {
                if(progressBar!=null){
                    progressBar.setProgress(progress);
                }
            }

            @Override
            public void onFail() {
                if(updateDialog!=null && updateDialog.isShowing()){
                    updateDialog.dismiss();
                }

            }

            @Override
            public void onSuccess() {
                if(updateDialog!=null && updateDialog.isShowing()){
                    updateDialog.dismiss();
                }
            }

            @Override
            public void onCancel() {
                if(updateDialog!=null && updateDialog.isShowing()){
                    updateDialog.dismiss();
                }
            }
            @Override
            public void onNoUpdateVersion() {
            }
        });
    }

    /**
     * description: 登出
     *
     * @author visitant
     * @time 2020/12/2 9:47
     */
    public void setLogin_out() {
        String str_tag = "1";
        FormBody formBody = new FormBody.Builder()
                .add("phone", sn.getString("phone", ""))
                .add("token", sn.getString("token", ""))
                .build();
        sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.logoutAddr);
    }


    protected void onStop() {
        super.onStop();
        if (this.isFinishing()) {
            myHandler.removeCallbacksAndMessages(null);
        }
    }



}
